﻿namespace gui {
    using System;
    using System.Collections.ObjectModel;
    using snat.model;

    /// <summary>
    /// Event View List element on the Events Monitor Tab
    /// </summary>
    public partial class EventListView {

        private ObservableCollection<EventItem> eventsList;
        public ObservableCollection<EventItem> EventsList {
            get { return eventsList; }
        }

        public EventListView() {
            InitializeComponent();

            // Set up events list for cross-thread binding
            eventsList = new ObservableCollection<EventItem>();
            DispatchingList<ObservableCollection<EventItem>, EventItem> dispatchingList = new DispatchingList<ObservableCollection<EventItem>, EventItem>(eventsList, Dispatcher);
            EventsListXAML.ItemsSource = dispatchingList;

            NetworkModel.Instance.MessageProcessed += guiOnMessageSend;
            NetworkModel.Instance.NodeAdded += guiOnNodeAdded;
            NetworkModel.Instance.EdgeAdded += guiOnEdgeAdded;
        }

        private void addToEventsList(string eventType, string eventName, string message) {
            EventItem e = new EventItem(EventsList.Count, NetworkModel.Instance.MessageProcessedCount, eventType, eventName, message);
            eventsList.Add(e);
            ScrollToBottom();
        }

        public void ScrollToBottom() {
            // Invoke this control's dispatcher to scroll to the bottom of the list
            this.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate() {
                EventsListXAML.ScrollIntoView(eventsList[(eventsList.Count - 1)]);
            }));
        }

        public void guiOnNodeAdded(int id, BaseNode n) {
            string eventType = "Network";
            string eventName = "Node Added";
            string message = "ID: " + n.ID + " Name: " + n.Name;
            addToEventsList(eventType, eventName, message);
        }

        public void guiOnEdgeAdded(Edge e) {
            string eventType = "Network";
            string eventName = "Edge Added";
            string message = "" + e.Source.Name + " >> " + e.Target.Name + " (" + e.Timestamp + ")";
            addToEventsList(eventType, eventName, message);
        }

        public void guiOnMessageSend(Message m) {
            string eventType = "Node";
            string eventName = "SendMsg (" + m.ID + ")";
            string message = "" + m.Sender.Name + " to " + m.Recipients.Count + " recipients on " + m.Timestamp;
            addToEventsList(eventType, eventName, message);
        }

    }
}